package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.pojos.SearchArticleVo;
import com.heima.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/29 10:55:06
 */
@Component
@Slf4j
public class KafkaListen {

    @Autowired
    private SearchService searchService;

    /**
     * 发布文章的时候更新es
     *
     * @param message
     */
    @KafkaListener(topics = "topic_add_es_article")
    public void onMessage(String message) {
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        searchService.addOrUpdate(searchArticleVo);
    }

    /**
     * 文章下架，删除es库中的数据
     *
     * @param message
     */
    @KafkaListener(topics = "topic_delete_es")
    public void deleteEs(String message) {
        String id = JSON.parseObject(message, String.class);
        searchService.deleteDoc(Long.valueOf(id));
    }

    /**
     * 文章上架添加数据
     *
     * @param message
     */
    @KafkaListener(topics = "topic_add_es")
    public void addEs(String message) {
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        searchService.addOrUpdate(searchArticleVo);
    }
}
